package com.example.culture.controller;

import com.example.culture.common.ServerResponse;
import com.example.culture.domain.*;
import com.example.culture.service.UserService;
import com.example.culture.util.EmptyUtil;
import com.example.culture.util.PropertiesUtils;
import com.example.culture.util.VideoUtil;
import com.example.culture.util.jwt.JwtUtil;
import com.example.culture.util.redis.RedisUtil;
import com.github.pagehelper.PageInfo;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;



@CrossOrigin
@Controller
@RequestMapping(value = "/user")
public class UserController {
    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    public UserService userService;

    @Autowired
    public RedisUtil redisUtil;



    /**
     * 获取角色身份
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getRole", method = RequestMethod.GET)
    public ServerResponse<List<Role>> getRole() {
        List<Role> roleList = userService.getRole();
        return ServerResponse.createBySuccess(roleList);
    }


    /**
     * 用户登录（返回类）
     * @param user（loginName，password，roleId）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ServerResponse<String> login(@RequestBody User user) {
        logger.info("用户登录信息" + user);
        User loginUser = userService.login(user);
        if (EmptyUtil.isNotEmpty(loginUser)) {
//            loginUser.setLoginTime(System.currentTimeMillis());
//            loginUser.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);//置空密码
            // todo important token有效期10个小时
            redisUtil.incr("visited",1);
            String token = JwtUtil.sign(loginUser, 600000L * 1000L * 6L);//token有效期10小时
            return ServerResponse.createBySuccess(token);
        } else {
            return ServerResponse.createByErrorMsg("账号名或者密码输入错误");
        }
    }

    /**
     * 注册用户
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ServerResponse<String> register(@RequestBody User user) {
        logger.info("注册用户" + user);
        return userService.register(user);
    }

    /**
     * 注册时 1、获取后台生成的邮箱验证码
     * 参数需要安全，接口安全
     *
     * @return
     */
    @RequestMapping(value = "/checkCode", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> sendEmailCode(@RequestBody String email) {
        JSONObject jsonObj = new JSONObject(email);
        logger.info("email" + jsonObj.getString("email"));
        //根据邮箱获取验证码
        return userService.generateCheckCode(jsonObj.getString("email"));
    }

    /**
     * 忘记密码时获取验证码 邮箱验证码
     */
    @RequestMapping(value = "/forgetCheckCode", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> forgetSendEmailCode(@RequestBody String email) {
        JSONObject jsonObj = new JSONObject(email);
        logger.info("忘记：email{}" , jsonObj.getString("email"));
        //根据邮箱获取验证码
        return userService.forgetSendEmailCode(jsonObj.getString("email"));
    }

    /**
     * 忘记密码时根据邮箱地址获取验证码 更新
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updatePassword(@RequestBody User user) {
        return userService.updatePassword(user);
    }

    /**
     * 评审账户登录
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "expertLogin", method = RequestMethod.POST)
    public ServerResponse<String> expertLogin() {
        logger.info("评审账号登录{}",new Date());
        User expertLoginUser = new User();
        expertLoginUser.setRoleId(4);
        expertLoginUser.setUsername("评审账户");
        expertLoginUser.setLoginName("pszh" + System.currentTimeMillis());
        expertLoginUser.setPassword("mima" + System.currentTimeMillis());
//        expertLoginUser.setLoginTime(System.currentTimeMillis());
        userService.expertLogin(expertLoginUser);
        logger.info("用户信息" + expertLoginUser);
        String token = JwtUtil.sign(expertLoginUser, 6000L * 1000L * 6L);//token有效期60分钟
        return ServerResponse.createBySuccess(token);
    }


    /**
     * 获取数据统计（用户总数量、实验总次数、实验总时长、总访问人数）
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/userAccount")
    @ResponseBody
    public ServerResponse userAccount(HttpServletRequest request, HttpServletResponse response){
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        return userService.accountUser();
    }

    /**
     * 获取角色人数比例
     * @param request
     * @return
     */
    @PostMapping(value = "/roleNums")
    @ResponseBody
    public ServerResponse roleNums(HttpServletRequest request){
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        return userService.roleNums();
    }

    /**
     * 管理员搜索用户+查看用户
     *
     * @param request
     * @param searchUser
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchUser", method = RequestMethod.POST)
    public ServerResponse<PageInfo> searchUser(HttpServletRequest request, @RequestBody String searchUser) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = new JSONObject(searchUser);
        Integer pageSize = jsonObject.getInt("pageSize");
        Integer pageNum = jsonObject.getInt("pageNum");
        Integer roleId=jsonObject.getInt("roleId");
        String classesName=jsonObject.getString("classesName");
        String username = jsonObject.getString("username");
        String school=jsonObject.getString("school");
        return userService.searchUser(pageNum, pageSize, username,school,classesName,roleId);
    }

    /**
     * 删除用户(根据用户编号)
     * @param request
     * @param deleteUser
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
    public ServerResponse deleteUser(HttpServletRequest request, @RequestBody String deleteUser) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = new JSONObject(deleteUser);
        Integer id = jsonObject.getInt("id");
        return userService.deleteUser(id);
    }


    /**
     * 新增后台用户管理记录（新增用户信息）
     */
    @RequestMapping(value = "/backend/add",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> addUser(@RequestBody User user, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.insertBackUser(user);
    }


    /**
     * 修改用户信息
     * @param user
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateUser",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updateUser(@RequestBody User user, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.updateUser(user);
    }

    /**
     * 级联获取班级以及分组(查询+搜索+分页)
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchClassesAndGroup",method = RequestMethod.POST)
    public ServerResponse getClassesAndGroup(HttpServletRequest request,@RequestBody String data){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject=new JSONObject(data);
        String classesName=jsonObject.getString("classesName");//班级名称
        Integer pageNum=jsonObject.getInt("pageNum");
        Integer pageSize=jsonObject.getInt("pageSize");
        return userService.searchClassesAndGroup(classesName,pageNum,pageSize);
    }

    /**
     * 级联获取班级以及分组
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getClassesAndGroup",method = RequestMethod.POST)
    public ServerResponse getClassesAndGroup(HttpServletRequest request){
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ") + 1);
//        User u = JwtUtil.unsign(jwt, User.class);
//        if (u == null) {
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        return userService.getClassesAndGroup();
    }


    /**
     * 提交实验成绩报告
     * @param request
     * @param experiment
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addExperiment",method = RequestMethod.POST)
    public ServerResponse addExperiment(HttpServletRequest request,@RequestBody Experiment experiment){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        experiment.setUserId(u.getId());
        experiment.setExperimentDuration(VideoUtil.secToTime(experiment.getU3dExperimentDuration()));
        return userService.addExperiment(experiment);
    }


    /**
     * 分页查询实验成绩报告信息
     * @param request
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getExperiment",method = RequestMethod.POST)
    public ServerResponse getExperiment(HttpServletRequest request,@RequestBody String data){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject=new JSONObject(data);
        Integer pageNum=jsonObject.getInt("pageNum");
        Integer pageSize=jsonObject.getInt("pageSize");
        String school=jsonObject.getString("school");//学校名称
        String classesName=jsonObject.getString("classesName");//班级名称
        String groupName=jsonObject.getString("groupName");//分组名称
        String username=jsonObject.getString("username");//用户名称
        return userService.getExperiment(pageNum,pageSize,school,classesName,groupName,username);
    }



}
